package com.uduemc.biso.module.basic.service.customer.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.github.pagehelper.page.PageMethod;
import com.uduemc.biso.core.extities.center.CustomerUser;
import com.uduemc.biso.module.basic.service.customer.mapper.CustomerUserMapper;
import com.uduemc.biso.module.basic.service.customer.service.CustomerUserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class CustomerUserServiceImpl implements CustomerUserService {

	@Autowired
	private CustomerUserMapper customerUserMapper;

	@Override
	public CustomerUser findByUsername(String username) {
		Example example = new Example(CustomerUser.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("username", username);
		return customerUserMapper.selectOneByExample(example);
	}

	@Override
	public CustomerUser findOne(Long id) {
		return customerUserMapper.selectByPrimaryKey(id);
	}

	@Override
	public CustomerUser insert(CustomerUser customerUser) {
		customerUserMapper.insert(customerUser);
		return findOne(customerUser.getId());
	}

	@Override
	public CustomerUser insertSelective(CustomerUser customerUser) {
		customerUserMapper.insertSelective(customerUser);
		return findOne(customerUser.getId());
	}

	@Override
	public CustomerUser updateById(CustomerUser customerUser) {
		customerUserMapper.updateByPrimaryKey(customerUser);
		return findOne(customerUser.getId());
	}

	@Override
	public CustomerUser updateByIdSelective(CustomerUser customerUser) {
		customerUserMapper.updateByPrimaryKeySelective(customerUser);
		return findOne(customerUser.getId());
	}

	@Override
	public List<CustomerUser> findAll(Pageable pageable) {
		int pageNumber = pageable.getPageNumber();
		int pageSize = pageable.getPageSize();
		PageMethod.startPage(pageNumber, pageSize);
		return customerUserMapper.selectAll();
	}

	@Override
	public void deleteById(Long id) {
		customerUserMapper.deleteByPrimaryKey(id);
	}

	@Override
	public CustomerUser findByNumberKey(String numberKey) {
		Example example = new Example(CustomerUser.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("numberKey", numberKey);
		return customerUserMapper.selectOneByExample(example);
	}

	@Override
	public String getCreateNumberKey() {
		long num = (long) ((Math.random() * 9 / 10) * Long.MAX_VALUE);
		String numberKey = String.valueOf(num);
		CustomerUser findByNumberKey = findByNumberKey(numberKey);
		if (findByNumberKey == null) {
			return numberKey;
		}
		return getCreateNumberKey();
	}

}
